/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import model.time.PlaylistRecordRestriction;
import config.Debug;
import config.Helper;
import config.Settings;

/**
 * 
 * @author Yang Wang <yang@digitalmenubox.com>
 */
public class PlaylistRecord implements Comparable<PlaylistRecord> {

	private int id;
	private int playlistId;
	private int pageId;
	private int containerId;
	private int contentId;
	private int recordOrder;
	private int pauseTime;

	public void setPauseTime(int pauseTime) {
		this.pauseTime = pauseTime;
	}

	private boolean clear;
	private boolean displayEventAfter;
	private boolean active;
	private Content content;
	private PlaylistRecordRestriction restriction;
	private int transition;

	public int getTransition() {
		return transition;
	}

	public void setTransition(int transition) {
		this.transition = transition;
	}

	public Content getContent() {
		return content;
	}

	public PlaylistRecordRestriction getRestriction() {
		return restriction;
	}

	public PlaylistRecord(int id) {
		this.createPlaylistRecordFromDatabaseById(id);
		this.content = new Content(this.contentId);
	}

	private void createPlaylistRecordFromDatabaseById(int id) {
		String sql = String.format("SELECT * FROM `playlist_record` WHERE `playlist_record_id`='%1$s' LIMIT 1;", id);
		Connection conn = Settings.getLocalDatabaseConnection();
		ResultSet result = null;
		Statement stmt = null;
		try {
			int numResults = Helper.getNumberOfResults(sql);
			if (numResults <= 0) {
				// throw new
				// com.mysql.jdbc.exceptions.MySQLDataException("There is no playlist record with id: "
				// + id);
				Debug.log("There is no playlist record with id: " + id, Debug.WARNING_LEVEL);
				return;
			}
			stmt = conn.createStatement();
			result = stmt.executeQuery(sql);
			result.first();
			this.id = id;
			this.recordOrder = result.getInt("record_order");
			this.playlistId = result.getInt("playlist_id");
			this.pageId = result.getInt("page_id");
			this.containerId = result.getInt("container_id");
			this.contentId = result.getInt("content_id");
			this.recordOrder = result.getInt("record_order");
			this.pauseTime = result.getInt("duration");
			this.transition = result.getInt("transition");
			this.active = (1 == result.getInt("active")) ? true : false;
			this.clear = (1 == result.getInt("clear")) ? true : false;
			this.displayEventAfter = (1 == result.getInt("displayeventafter")) ? true : false;

			// this block will create a PlaylistRecordRestriction
			String[] days = result.getString("days").split(",");
			Calendar fTime = Calendar.getInstance();
			Calendar tTime = Calendar.getInstance();
			DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM);
			Date fromDate = result.getDate("from_date");
			Time fromTime = result.getTime("from_time");

			fTime.set(fromDate.getYear() + 1900, fromDate.getMonth(), fromDate.getDate(), fromTime.getHours(), fromTime.getMinutes(), fromTime.getSeconds());

			Date toDate = result.getDate("to_date");
			Time toTime = result.getTime("to_time");
			tTime.set(toDate.getYear() + 1900, toDate.getMonth(), toDate.getDate(), toTime.getHours(), toTime.getMinutes(), toTime.getSeconds());
			this.restriction = new PlaylistRecordRestriction(fTime, tTime, days);

		} catch (SQLException ex) {
			Logger.getLogger(Playlist.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			try {
				if (result != null)
					result.close();
				if (stmt != null)
					stmt.close();
			} catch (SQLException ex) {
				Logger.getLogger(PlaylistRecord.class.getName()).log(Level.SEVERE, null, ex);
			}

		}
	}

	/*
	 * @returns true if this record can currently be played
	 */
	public boolean isPlayableNow() {
		if (Container.containerExists(this.containerId) && Content.contentExists(this.contentId) && new Content(this.contentId).hasValidContent() && this.isActive() && !this.content.hasUpdate()) {
			return this.restriction.isPlayableNow();
		} else {
			return false;
		}
	}

	public static void main(String[] args) {
		PlaylistRecord pr = new PlaylistRecord(3);
		System.out.println(pr.isPlayableNow());

		// System.out.println(pr.getRestriction().getDuration());
	}

	public boolean isActive() {
		return active;
	}

	public boolean isClear() {
		return clear;
	}

	public int getContainerId() {
		return containerId;
	}

	public int getContentId() {
		return contentId;
	}

	public boolean isDisplayEventAfter() {
		return displayEventAfter;
	}

	public int getPauseTime() {
		return pauseTime;
	}

	public int getId() {
		return id;
	}

	public int getPageId() {
		return pageId;
	}

	public int getPlaylistId() {
		return playlistId;
	}

	public int getRecordOrder() {
		return recordOrder;
	}

	@Override
	public String toString() {

		return String.format("PlaylistRecord: %1$-7d Container: %2$-7s Pause: %3$-4d Page: %4$-6d %5$-50s", this.getId(),
				new Container(this.getContainerId()).getName(), this.getPauseTime(), this.getPageId(), (this.getContent().toString().length() > 50) ? this
						.getContent().toString().substring(0, 50) : this.getContent());
		// return "PlaylistRecord " + this.getId() + " Container: " +
		// this.getContainerId() + " Pause: " + this.getPauseTime() + " " +
		// this.getContent() + " Page: " + this.getPageId() ;
		// return this.getId() + ") " + this.getRestriction().getDuration();
	}

	public String getFullInfo() {

		return null;
	}

	@Override
	public int compareTo(PlaylistRecord pr) {
		if (this.isActive() && !pr.isActive()) {
			return -1;
		} else if (!this.isActive() && pr.isActive()) {
			return 1;
		} else if (this.isActive() && pr.isActive()) {
			if (this.getRecordOrder() - pr.getRecordOrder() == 0) {
				return (this.getId() - pr.getId());
			} else {
				return this.getRecordOrder() - pr.getRecordOrder();
			}
		} else {
			return 0;
		}
	}
}
